package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.SMSUtils;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session) {
        log.info(user.toString());
        //使用工具类生成验证码
        //String code = String.valueOf(ValidateCodeUtils.generateValidateCode(6));
        //使用阿里云带的api发送信息
        // SMSUtils.sendMessage("生活记录","SMS_209163022",user.getPhone(),code);
        session.setAttribute("code", "1234");
        return R.success("发送成功");
    }

    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession session) {
        String phone = (String) map.get("phone");
        Object code = map.get("code");

        //对比 前端输入的验证码 和session中的验证密码
        if (code.equals(session.getAttribute("code"))) {
            session.setAttribute("user", phone);
            LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(User::getPhone, phone);
            User user = userService.getOne(lambdaQueryWrapper);

            //数据库中没有查到user
            if (user == null) {
                //用户为第一次登录
                //将用户信息保存到数据库
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            session.setAttribute("user", user.getId());

            if (user.getStatus()!=1){
                return  R.error("登录失败");
            }
            //将用户信息返回
            return R.success(user);
        }
        return R.error("登录失败");
    }

}
